<script setup>
import { hiprint, defaultElementTypeProvider } from "vue-plugin-hiprint";
import { GetConfigAPI } from "@/api/system/printConfig";
import View from "./view.vue";
import "../../../../public/print-lock.css";
import useUserStore from "@/store/modules/user";
import dayjs from "dayjs";
const emit = defineEmits();
const { proxy } = getCurrentInstance();
const useUser = useUserStore();
const props = defineProps({
  // 数据
  printData: {
    type: [Object, Array],
    default: () => {},
  },
  // 模板ID
  templateId: {
    type: String || Number,
    default: "",
  },
  copies: {
    type: String || Number,
    default: "1",
  },
  zoom: {
    type: Number,
    default: 1,
  },
});

const viewRef = ref(null);

const config = reactive({
  width: "",
  height: "",
  hiprintConfig: "",
  hiprintTemplate: "",
});
const timer = ref(null);
// 获取打印纸宽高
const initPrint = () => {
  console.log("%c打印内容：=>", "color:red");
  console.log(props.printData);

  // 判断数组时是否有数据
  if (Array.isArray(props.printData) && props.printData.length <= 0) {
    loading.value = false;
    // proxy.warningMsg('p-printView组件:打印数据为空=>' + props.printData)
    return;
  }

  // 判断对象时是否有数据
  if (typeof props.printData == "object") {
    if (Object.keys(props.printData).length == 0) {
      loading.value = false;

      // proxy.warningMsg('p-printView组件:打印数据为空=>' + props.printData)
      return;
    }
  }
  // 判断是否数据结构错误
  if (typeof props.printData != "object" && !Array.isArray(props.printData)) {
    loading.value = false;

    proxy.warningMsg("p-printView组件:打印数据结构错误=>" + props.printData);
    return;
  }

  try {
    if (Array.isArray(props.printData)) {
      props.printData.forEach((item) => {
        // item.printBy = useUser.name

        item.printTime = dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss");
      });
    } else {
      // props.printData.printBy = useUser.name
      props.printData.printTime = dayjs(new Date()).format(
        "YYYY-MM-DD hh:mm:ss"
      );
    }
    config.width = config.hiprintTemplate.panels[0].width + 10;
    config.height = config.hiprintTemplate.panels[0].height + 10;
    config.hiprintTemplate.panels[0].scale = props.zoom;

    config.hiprintConfig = new hiprint.PrintTemplate({
      template: config.hiprintTemplate,
    });

    $("#preview_content_design").html(
      config.hiprintConfig.getHtml(props.printData)
    );
    if (!hiprint.hiwebSocket.opened) {
      printLink();
    }
    loading.value = false;
  } catch (err) {
    console.log(err, "errrrrr");
  }
};
let tiemr = null;
// 连接打印机
const printLink = () => {
  tiemr = setInterval(() => {
    if (hiprint.hiwebSocket.opened) {
      clearInterval(tiemr);
      // proxy.successMsg('打印机连接成功！')
      return;
    }
    hiprint.hiwebSocket.setHost(import.meta.env.VITE_APP_BASE_PRINT);
  }, 1000);
};

// 打印
const print = () => {
  return new Promise(async (resolve, reject) => {
    if (!props.printData)
      return proxy.warningMsg("p-printView组件:打印数据为空");
    if (Array.isArray(props.printData)) {
      props.printData.forEach((item) => {
        item.printBy = useUser.name;
        item.printTime = dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss");
      });
    } else {
      props.printData.printBy = useUser.name;
      props.printData.printTime = dayjs(new Date()).format(
        "YYYY-MM-DD hh:mm:ss"
      );
    }

    await getConfig();
    proxy.$modal.loading("打印中，请稍后...");
    // 刷新获取 打印机列表 !! 需要已连接 "直接打印客户端"
    hiprint.refreshPrinterList((list) => {
      console.log(list);
    });
    // 判断是否已成功连接
    if (!hiprint.hiwebSocket.opened) {
      hiprint.hiwebSocket.setHost(import.meta.env.VITE_APP_BASE_PRINT);
      // 重新连接客户端  连接局域网内的客户端
      proxy.warningMsg("打印机未连接，正在尝试连接");
      proxy.$modal.closeLoading();
      return;
    }

    if (!props.templateId) {
      proxy.$modal.closeLoading();
      proxy.warningMsg("p-printView组件:请传入传入模板id!");
      return;
    }
    if (!config?.hiprintConfig?.print2) {
      await getConfig();
      proxy.warningMsg("打印失败,没有找到模板！");
      proxy.$modal.closeLoading();
      return;
    }
    // 重新初始化
    initPrint();
    config.hiprintConfig.print2(props.printData, {
      setDuplexPrint: false,
      title: import.meta.env.VITE_PRINT_Title,
      copies: Number(props.copies), // 打印份数 默认 1
      orient: 2,
    });

    config.hiprintConfig.on("printSuccess", function (data) {
      emit("printYes");
      proxy.successMsg("打印成功" + JSON.stringify(data));
      proxy.$modal.closeLoading();

      resolve("完成");
    });

    config.hiprintConfig.on("printError", function (data) {
      proxy.warningMsg("打印失败，失败参数：" + JSON.stringify(data));
      proxy.$modal.closeLoading();
      reject(data);
    });
  });
};

// 预览
const preView = () => {
  if (!props.templateId) return proxy.warningMsg("请选择对应标签");
  config.hiprintTemplate.panels[0].scale = 1;
  viewRef.value.isShow1(config.hiprintTemplate, props.printData);
};

// 转PDF
const toPdf = () => {
  hiprintTemplate.toPdf(printConfig.printData, "打印预览pdf");
};

const loading = ref(false);
// 配置 弹窗
const getConfig = async (templateId) => {
  loading.value = true;
  try {
    const { data: res } = await GetConfigAPI(props.templateId || templateId);
    if (!res.statsJson) {
      proxy.warningMsg("请到打印模版配置模版内容！");
      throw new Error("p-printView组件:未配置内容");
    }
    config.hiprintTemplate = JSON.parse(res.statsJson);

    clearInterval(timer.value);
    initPrint();
  } catch {
    loading.value = false;
  } finally {
  }
};

watch(
  () => props.templateId,
  (val) => {
    if (val) {
      getConfig();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

/**
 * 当数据有变化时重新加载模版
 */

watch(
  () => props.printData,
  (val) => {
    nextTick(() => {
      if (val && props.templateId) getConfig();
    });
  },
  {
    deep: true,
    immediate: true,
  }
);
defineExpose({ print, getConfig });
</script>

<template>
  <div style="width: 100%; overflow-y: auto">
    <div
      v-loading="loading"
      @click.stop="preView"
      class="print-view"
      :style="`height:${config.height}mm;width:${config.width}mm`"
    >
      <el-empty v-if="!props.templateId" description="description" />
      <div v-else id="preview_content_design"></div>
    </div>
    <View ref="viewRef" />
  </div>
</template>

<style lang="scss" scoped>
.print-view {
  transition: all 0.2s;

  cursor: pointer;
}

.print-view ::v-deep .hiprint-printPanel {
  border: 2px solid #d2cdcd;
  border-radius: 10px;
  margin-bottom: 0.3125rem;
}
</style>
